<?php
namespace app\controller;

use app\BaseController;
use think\facade\Db;
use think\facade\Session;

class Product extends BaseController
{
    // 商品详情页
    public function detail() {
        $pro_out_no = input('get.out_no');
        $data['user'] = Session::get('user');
        $data['item'] = Db::table('product_sku')->where('out_no', $pro_out_no)->find();
        $data['name_value'] = json_decode($data['item']['name_value'], true);
        $skus = Db::table('product_sku')->where('pro_id', $data['item']['pro_id'])->select();
        $name_ids = [];
        $value_ids = [];
        foreach($skus as $sku) {
            $name_value = json_decode($sku['name_value'], true);
            foreach($name_value as $name_id => $value_id) {
                $name_ids[] = $name_id;
                $value_ids[$name_id][] = $value_id;
            }
        }
        $data['name_ids'] = $name_ids;
        $data['value_ids'] = $value_ids;
        $property_names = Db::table('property_names')->whereIn('id', array_keys($data['name_value']))->column('*', 'id');
        $property_values = Db::table('property_values')->whereIn('name_id', array_keys($data['name_value']))->column('*', 'id');
        $data['property_names'] = array_map(function($item) use ($property_values) {
            $item['property_values'] = array_filter($property_values, function($elem) use ($item) {
                return $item['id'] === $elem['name_id'];
            });
            return $item;
        }, $property_names);
        return view('/product/detail', $data);
    }

    // 点击动态获取sku
    public function get_sku() {
        $properties = input('post.properties');
        $name_value = array_reduce($properties, function($res, $next) {
            $res[$next['name_id']] = $next['value_id'];
            return $res;
        }, []);
        ksort($name_value);
        $name_value = json_encode($name_value);
        $sku = Db::table('product_sku')->where('name_value', $name_value)->find();
        !$sku && exit(json_encode(['code' => 1, 'msg' => '该商品缺货']));
        exit(json_encode(['code' => 0, 'data' => $sku]));
    }

    // 加入购物车
    public function add_cart() {
        $user = Session::get('user');
        !$user && exit(json_encode(['code' => 401, 'msg' => '您还未登录，请先登录']));
        $data['uid'] = $user['id'];
        $data['sku_out_no'] = (int)input('post.sku_out_no');
        $data['count'] = input('post.count');
        $data['add_time'] = time();
        Db::table('carts')->insert($data);
        exit(json_encode(['code' => 0, 'msg' => '添加成功']));
    }
}